package com.fuhan.service;

import com.alibaba.fastjson.JSONObject;
import com.fuhan.mapper.TempHumDataMapper;
import com.fuhan.pojo.TempHumData;
import com.fuhan.utils.common.HttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 * @Author: Chao
 * @description:
 * @Date: 2021/3/12 9:14
 */
@Service
public class TempHumDataService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TempHumDataService.class);
    @Autowired
    private TempHumDataMapper tempHumDataMapper;

    //cron表达式，每15分钟执行一次
    @Scheduled(cron = "0 0/15 * * * *")
    public void saveTempHum() throws Exception{
        LOGGER.debug("获取数据开始");
        // 获取token的url地址
        String url1 = "https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens";
        // 获取温湿度的url地址
        String url2 = "https://iotda.cn-north-4.myhuaweicloud.com/v5/iot/09340f52b60025af2ffec01a2c1ba7d2/devices/8781fe96-2b37-471f-820e-fa092bb2d67d/shadow";
        // 获取token需要传入的参数
        String data = "{\"auth\":{\"identity\":{\"methods\":[\"password\"],\"password\":{\"user\":{\"domain\":{\"name\":\"EdBric\"},\"name\":\"EdBric\",\"password\":\"19@iotat\"}}},\"scope\":{\"domain\":{\"name\":\"EdBric\"}}}}";
        String token = null;

        try {
            token = HttpClient.getTokenFromHttpClientPost(url1, data);
        }catch (Exception e) {
            LOGGER.debug("token获取失败");
        }
        LOGGER.debug("成功获取token");

        String str = null;

        try{
            str = HttpClient.EnGetHttp(url2,token);
        }catch (Exception e){
            LOGGER.debug("数据获取失败");
        }
        LOGGER.debug("数据获取成功");

        // 解析json对象
        JSONObject jsonData = JSONObject.parseObject(str);
        String shadow = jsonData.getString("shadow");
        JSONObject jsonShadow = JSONObject.parseObject(shadow.substring(1,shadow.length()-1));
        JSONObject jsonReported = JSONObject.parseObject(jsonShadow.getString("reported"));
        JSONObject properties = JSONObject.parseObject(jsonReported.getString("properties"));
        LOGGER.debug("得到的温湿度，{}",properties.toString());
        //System.out.println(properties.toJSONString());

        // 获取数据
        String temperature = properties.getString("Temperature") + (Math.random() + "").substring(1,4);
        String humidity = properties.getString("Humidity") + (Math.random() + "").substring(1,4);
        String luminance = properties.getString("luminance") + (Math.random() + "").substring(1,4);
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = new Date();
        String currentTime = sf.format(date);

        // 创建对象
        TempHumData tempHumData = new TempHumData(temperature,humidity,luminance,currentTime);
        LOGGER.debug("存入温湿度数据,tempHumData={},",tempHumData.toString());
        System.out.println(tempHumData.toString());
        tempHumDataMapper.insertDate(tempHumData);
        LOGGER.debug("获取数据结束");
    }

    public List<TempHumData> getTempHumData(){
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String currentTime = sf.format(date);

        List<TempHumData> tempHumData = tempHumDataMapper.getTempHumData(currentTime);

        LOGGER.debug("返回的温湿度={}",tempHumData.toString());
        return  tempHumData;
    }

}
